package com.yumei.trader.gym.page;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsResponseListener;
import com.yumei.trader.gym.R;
import com.yumei.trader.gym.client.BasePage;
import com.yumei.trader.gym.dbase.sqlite.SqliteActObject;
import com.yumei.trader.gym.google.BillingResultCallBack;
import com.yumei.trader.gym.google.GoogleConst;
import com.yumei.trader.gym.google.GoogleHelper;
import com.yumei.trader.gym.client.TGApplication;
import com.yumei.trader.gym.object.ProductObj;

import java.util.ArrayList;
import java.util.List;


public class PageAppPay extends BasePage {

    private TextView starNumber;
    private TextView subscribePrice;
    private TextView price01Txt, price02Txt, price03Txt, price04Txt;
    private RelativeLayout progressLayout;

    private GoogleHelper googleObject;
    private ArrayList<SkuDetails> skuDetailArr = new ArrayList<>();
    private int choosePosition = -1;
    private ArrayList<ProductObj> productArr = new ArrayList<>();

    private TGApplication mApp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mApp = (TGApplication) this.getApplication();

        googleObject = GoogleHelper.initInstance(this, GoogleConst.base64EncodedPublicKey);

        setContentView(R.layout.page_pay_center);
        transparentBar();
        registerView();
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (mApp.isConnectGoogle) {
            checkProduct();
        } else {
            connectToGoogle();
        }
    }

    @SuppressLint("SetTextI18n")
    private void registerView() {

        starNumber = this.findViewById(R.id.pay_center_star_number);
        loadUserStar();

        ImageView shopImg = this.findViewById(R.id.pay_center_shop);
        // shopImg.startAnimation(wobbleAnimation(3));

        subscribePrice = this.findViewById(R.id.pay_center_subscribe_price);
        subscribePrice.setText(PageAppPay.this.getResources()
                .getString(R.string.str_subscription_price).replace("####", GoogleConst.SubPrice));

        TextView subscriptionTxt = this.findViewById(R.id.pay_center_subscription_hint);
        subscriptionTxt.setMovementMethod(ScrollingMovementMethod.getInstance());

        price01Txt = this.findViewById(R.id.pay_center_01_product_price);
        price02Txt = this.findViewById(R.id.pay_center_02_product_price);
        price03Txt = this.findViewById(R.id.pay_center_03_product_price);
        price04Txt = this.findViewById(R.id.pay_center_04_product_price);

        progressLayout = this.findViewById(R.id.progress_layout);
        progressLayout.setVisibility(View.GONE);

        this.findViewById(R.id.pay_back_layout).setOnClickListener(clickListener);
        this.findViewById(R.id.pay_center_subscribe_layout).setOnClickListener(clickListener);
        this.findViewById(R.id.pay_center_01_product_layout).setOnClickListener(clickListener);
        this.findViewById(R.id.pay_center_02_product_layout).setOnClickListener(clickListener);
        this.findViewById(R.id.pay_center_03_product_layout).setOnClickListener(clickListener);
        this.findViewById(R.id.pay_center_04_product_layout).setOnClickListener(clickListener);

        productArr.add(new ProductObj(GoogleConst.productId_star_01, "$3.99", 20));
        productArr.add(new ProductObj(GoogleConst.productId_star_02, "$5.99", 40));
        productArr.add(new ProductObj(GoogleConst.productId_star_03, "$9.99", 80));
        productArr.add(new ProductObj(GoogleConst.productId_star_04, "$14.99", 120));

        initProductInfo();
    }

    @SuppressLint("SetTextI18n")
    private void loadUserStar() {
        starNumber.setText("x" + (int) SqliteActObject.getInstance(this).getAccount(mApp.getUserId()).useTimes);
    }

    /**
     * 主体UI点击时间控制中枢
     */
    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            if (v.getId() == R.id.pay_back_layout) {
                onBackAction();

            } else if (v.getId() == R.id.pay_center_subscribe_layout) {
                onSubscribeAction();

            } else if (v.getId() == R.id.pay_center_01_product_layout) {
                goToPayAction(0);

            } else if (v.getId() == R.id.pay_center_02_product_layout) {
                goToPayAction(1);

            } else if (v.getId() == R.id.pay_center_03_product_layout) {
                goToPayAction(2);

            } else if (v.getId() == R.id.pay_center_04_product_layout) {
                goToPayAction(3);

            }
        }
    };

    private void goToPayAction(int index) {
        if (mApp.isConnectGoogle) {
            choosePosition = index;
            toPayAction();
        } else {
            startActivity(PageServiceConnect.class);
        }
    }

    private void initProductInfo() {
        price01Txt.setText(productArr.get(0).mProductPrice);
        price02Txt.setText(productArr.get(1).mProductPrice);
        price03Txt.setText(productArr.get(2).mProductPrice);
        price04Txt.setText(productArr.get(3).mProductPrice);
    }

    private void onSubscribeAction() {

        progressLayout.setVisibility(View.VISIBLE);

        googleObject.executeQuerySkuDetails(GoogleConst.productId, new SkuDetailsResponseListener() {
            @Override
            public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> skuDetailsList) {

                int code = billingResult.getResponseCode();

                if (BillingClient.BillingResponseCode.OK == code) {

                    for (SkuDetails sku : skuDetailsList) {

                        if (sku.getSku().equalsIgnoreCase(GoogleConst.productId)) {

                            googleObject.setResultCallback(subscribeCallBack);
                            googleObject.launchBillingFlow(PageAppPay.this, sku);
                        }
                    }
                } else {
                    progressLayout.setVisibility(View.GONE);
                    startActivity(PageServiceConnect.class);
                }
            }
        });
    }

    private BillingResultCallBack subscribeCallBack = new BillingResultCallBack() {

        @Override
        public void onResult(int code, List<Purchase> purchases) {

            if (BillingClient.BillingResponseCode.OK == code) {

                if (purchases != null) {
                    for (Purchase p : purchases) {
                        if (p.getSkus().contains(GoogleConst.productId)) {

                            progressLayout.setVisibility(View.GONE);
                            TGApplication.vipUser = true;
                            onBackAction();
                        }
                    }
                }
            } else {
                progressLayout.setVisibility(View.GONE);
            }
        }
    };

    private void connectToGoogle() {

        googleObject.connectGooglePlay(new BillingClientStateListener() {

            @Override
            public void onBillingSetupFinished(BillingResult billingResult) {
                int code = billingResult.getResponseCode();
                if (BillingClient.BillingResponseCode.OK == code) {
                    mApp.isConnectGoogle = true;
                    checkProduct();
                } else {
                    mApp.isConnectGoogle = false;
                    startActivity(PageServiceConnect.class);
                }
            }

            @Override
            public void onBillingServiceDisconnected() {
            }
        });
    }

    private void checkProduct() {

        List<String> skuArr = new ArrayList<>();
        skuArr.add(GoogleConst.productId_star_01);
        skuArr.add(GoogleConst.productId_star_02);
        skuArr.add(GoogleConst.productId_star_03);
        skuArr.add(GoogleConst.productId_star_04);

        googleObject.executeQuerySkuDetails(skuArr, new SkuDetailsResponseListener() {
            @Override
            public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> skuDetailsList) {

                int code = billingResult.getResponseCode();

                if (BillingClient.BillingResponseCode.OK == code) {

                    for (SkuDetails skuDetails : skuDetailsList) {

                        String sku = skuDetails.getSku();
                        String price = skuDetails.getPrice();

                        for (ProductObj element : productArr) {

                            if (sku.equals(element.mProductId)) {
                                skuDetailArr.add(skuDetails);
                                element.mProductPrice = price;
                            }
                        }
                    }

                    initProductInfo();
                }
            }
        });
    }

    private void toPayAction() {

        String productId = productArr.get(choosePosition).mProductId;

        for (SkuDetails sku : skuDetailArr) {
            if (productId.equals(sku.getSku())) {
                googleObject.setResultCallback(purchaseCallBack);
                googleObject.launchBillingFlow(PageAppPay.this, sku);
            }
        }
    }

    private BillingResultCallBack purchaseCallBack = new BillingResultCallBack() {

        @Override
        public void onResult(int code, List<Purchase> purchases) {

            if (BillingClient.BillingResponseCode.OK == code) {
                addStartAction(productArr.get(choosePosition).mProductStar);
            }
        }
    };

    private void addStartAction(int num) {

        SqliteActObject.getInstance(this).updateTimes(mApp.getUserId(), num);
        loadUserStar();
        showToast(" Purchase successful ");
    }

    /**
     * 晃动动画
     */
    public Animation wobbleAnimation(int counts) {
        Animation rotateAnimation = new RotateAnimation(0, 20,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setInterpolator(new CycleInterpolator(counts));
        rotateAnimation.setRepeatCount(-1);
        rotateAnimation.setDuration(1500);
        return rotateAnimation;
    }

}
